<?php

namespace app\admin\controller\demand;

use app\common\controller\Backend;
use think\Db;
/**
 * 需求中心
 *
 * @icon fa fa-circle-o
 */
class Requirements extends Backend
{

    /**
     * Requirements模型对象
     * @var \app\admin\model\demand\Requirements
     */
    protected $model = null;
    protected $finance = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\demand\Requirements;
        $this->finance  = new \app\admin\model\finance_menu\Finance;

        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("natureList", $this->model->getNatureList());
        $this->view->assign("scaleList", $this->model->getScaleList());
        $this->view->assign("classificationList", $this->model->getClassificationList());
        $this->view->assign("relationList", $this->model->getRelationList());
        $this->view->assign("sexDataList", $this->model->getSexDataList());
        $this->view->assign("ageList", $this->model->getAgeList());
        $this->view->assign("participantList", $this->model->getParticipantList());
        $this->view->assign("activityGoalList", $this->model->getActivityGoalList());
        $this->view->assign("managementList", $this->model->getManagementList());

        $this->view->assign("paymentMethodList", $this->model->getPaymentMethodList());
        $this->view->assign("billingTypeList", $this->model->getBillingtypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','type','title','createtime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //print_r($params);exit;
                $params = $this->preExcludeFields($params);
                $data_list = [];
                for($i=1;$i<=$params['number'];$i++)
                {
                    $all = [];
                    foreach($params['start_time_xc'.$i] as $k=>$v)
                    {
                        $data = [];
                        $data['start_time'] = $v;
                        $data['end_time'] = $params['end_time_xc'.$i][$k];
                        $data['content'] = $params['content_xc'.$i][$k];
                        $data['addr'] = $params['addr_xc'.$i][$k];
                        $data['remark'] = $params['remark_xc'.$i][$k];
                        $data['number'] = $i;
                        $all[] = $data;
                    }

                    $data_list[$i] = $all;
                }
                $data_number = count($data_list);
                $params['schedule'] = json_encode($data_list);

                if(!empty($params['age_composition']))
                {
                    $params['age_composition'] = implode(',',$params['age_composition']);
                }
                if(!empty($params['participant']))
                {
                    $params['participant'] = implode(',',$params['participant']);
                }
                if(!empty($params['activity_goal']))
                {
                    $params['activity_goal'] = implode(',',$params['activity_goal']);
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $teacher = Db::name('teacher')->field('type,fee_z,fee_f')->where('id',$params['teacher_id'])->find();//教师详情
                $field = Db::name('field')->where('id',$params['field_id'])->field('supporting_services,price')->find();//场地详情
                $prop = Db::name('prop')->field('price,quantity_start,quantity_end')->where('id',$params['field_id'])->find();//场地详情

                $total_price = intval($teacher['fee_z'])+intval($field['price'])+intval($prop['price']);


                $cost_fee = [
                    [
                        'title'=>'教师费',
                        'describe'=>$teacher['type'],
                        'price'=>$teacher['fee_z'],
                    ],
                    [
                        'title'=>'场地费',
                        'describe'=>$field['supporting_services'],
                        'price'=>$field['price'],
                    ],
                    [
                        'title'=>'道具租赁',
                        'describe'=>'物资管理费',
                        'price'=>$prop['price'],
                    ]
                ];

                $time = time();
                $new_data = [];
                $new_data['corporate_name'] = $params['title'];
                $new_data['city'] = $params['city'];
                $new_data['activity_end_time'] = $params['activity_end_time'];
                $new_data['activity_start_time'] = $params['activity_start_time'];
                $new_data['total_sales_price'] = $params['total_fee'];
                $new_data['number'] = $params['number'];
                $new_data['payment_method'] = $params['payment_method'];
                $new_data['day'] = $data_number;
                $new_data['prepayments'] = $params['prepayments'];
                $new_data['cost_quotation'] = $params['cost_quotation'];
                $new_data['total_fee'] = $params['total_fee'];
                $new_data['total_estimated_cost'] = $total_price;
                //$new_data['total_cost'] = $total_price;
                $new_data['cost_fee'] = $total_price;
                $new_data['cost'] = json_encode($cost_fee);
                $new_data['createtime'] = $time;
                $new_data['updatetime'] = $time;

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::name('finance')->insert($new_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $data_list = [];
                for($i=1;$i<=$params['number'];$i++)
                {
                    $all = [];
                    foreach($params['start_time_xc'.$i] as $k=>$v)
                    {

                        $data = [];
                        $data['start_time'] = $v;
                        $data['end_time'] = $params['end_time_xc'.$i][$k];
                        $data['content'] = $params['content_xc'.$i][$k];
                        $data['addr'] = $params['addr_xc'.$i][$k];
                        $data['remark'] = $params['remark_xc'.$i][$k];
                        $data['number'] = $i;
                        $all[] = $data;
                    }

                    $data_list[$i] = $all;
                }
                $params['schedule'] = json_encode($data_list);
                if(!empty($params['age_composition']))
                {
                    $params['age_composition'] = implode(',',$params['age_composition']);
                }
                if(!empty($params['participant']))
                {
                    $params['participant'] = implode(',',$params['participant']);
                }
                if(!empty($params['activity_goal']))
                {
                    $params['activity_goal'] = implode(',',$params['activity_goal']);
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['schedule']!='')
        {
            $row['schedule'] = json_decode($row['schedule'],true);
        }
        //print_r($row['schedule']);exit;
        $row['teacher_title'] = Db::name('teacher')->where('id',$row['teacher_id'])->value('name');
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
